package org.nowcoder.leetcode.bit;

/**
 * Title  : 201. Bitwise AND of Numbers Range
 * Source : https://leetcode.cn/problems/bitwise-and-of-numbers-range/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-08-26
 */

public class LeetCode_201 {
    public int rangeBitwiseAnd(int left, int right) {
        //超时
        // int result = left++;
        // while (left <= right) {
        //     result &= left++;
        // }
        // return result;

        //Kernighan 算法: 每次进行 n & (n - 1) 操作，都会将 n 的二进制表示中最右边的一个 1 变成 0
        while (left < right) {
            right = right & (right - 1);
        }
        return right;
    }
}
